<template>
  <div>
    <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>

      <el-card>
        <!-- 添加角色 区域 -->
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="primary"
                       @click="addDialogVisible = true">添加角色</el-button>
          </el-col>
        </el-row>

        <!-- 角色列表区域 -->
        <el-table :data="rolesList"
                  border
                  stripe>
          <!-- 展开列表 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '' ,'vcenent']"
                      v-for="(item1,i1) in scope.row.children "
                      :key="item1.id">
                <!-- 一级权限 -->
                <el-col :span="5">
                  <el-tag closable
                          @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>

                <!-- 二级/三级权限 -->
                <el-col :span="19">
                  <!-- for循环 二级权限 -->
                  <el-row :class="[ i2 === 0 ? '' : 'bdtop','vcenent']"
                          v-for="(item2,i2) in item1.children"
                          :key="item2.id">
                    <el-col :span="6">
                      <el-tag type="success"
                              closable
                              @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级权限  -->
                    <el-col :span="18">
                      <el-tag type="warning"
                              v-for="(item3) in item2.children"
                              :key="item3.id"
                              closable
                              @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>

              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列表 -->
          <el-table-column type="index"
                           label="#"></el-table-column>
          <el-table-column label="角色名称"
                           prop="roleName"></el-table-column>
          <el-table-column label="角色描述"
                           prop="roleDesc"></el-table-column>
          <el-table-column label="操作"
                           width="300px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="small"
                         @click="showEditDialog(scope.row.id)">编辑</el-button>
              <!-- 删除按钮 -->
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="small"
                         @click="removeUserById(scope.row.id)">删除</el-button>

              <!-- 分配角色 -->
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="small"
                         @click="showSetRightDialog(scope.row)">分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加角色的对话框 -->
      <el-dialog title="添加角色"
                 :visible.sync="addDialogVisible"
                 width="50%"
                 @close="addDialogClosed">
        <!-- 内容主体区域 -->
        <!-- 表单区域 -->
        <el-form label-width="100px"
                 :model="rolesForm"
                 :rules="rolesFormRules"
                 ref="rolesFormRef"
                 status-icon>

          <!-- 角色名 -->
          <el-form-item label="角色名称"
                        prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>
          <!-- 角色描述 -->
          <el-form-item label="角色描述"
                        prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 局部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改角色的对话框 -->
      <el-dialog title="修改角色"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close="editDialogClosed">
        <!-- 内容主体区域 -->
        <!-- 表单区域 -->
        <el-form label-width="100px"
                 :model="editRolesForm"
                 :rules="rolesFormRules"
                 ref="editRolesFormRef"
                 status-icon>

          <!-- 角色名 -->
          <el-form-item label="角色名称"
                        prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <!-- 角色描述 -->
          <el-form-item label="角色描述"
                        prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 局部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!--分配角色的对话框 -->
      <el-dialog title="分配权限"
                 :visible.sync="setRightDialogVisible"
                 width="50%"
                 @close="setRightDialogClosed">
        <!-- 树形控件区域 -->
        <el-tree :data="rightsList"
                 :props="treeProps"
                 show-checkbox
                 node-key="id"
                 default-expand-all
                 :default-checked-keys="defKeys"
                 ref="treeRef"></el-tree>

        <!-- 局部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="allotRigths">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 添加角色对话框的显示隐藏
      addDialogVisible: false,
      // 修改角色对话框的显示隐藏
      editDialogVisible: false,
      // 分配角色对话框的显示隐藏
      setRightDialogVisible: false,
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      editRolesForm: {
      },
      // 添加表单的规则验证
      rolesFormRules: {
        // 验证角色名是否合法
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 权限树列表
      rightsList: [],
      // 权限树渲染规则
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 分配对话框中确认后分配角色的对应id
      roleId: ''
    }
  },
  created () {
    // 获取所有角色
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 监听添加角色对话框的事件
    addDialogClosed () {
      // 对话框关闭时清空表单的数据
      this.$refs.rolesFormRef.resetFields()
    },
    editDialogClosed () {
      // 对话框关闭时清空表单的数据
      this.$refs.editRolesFormRef.resetFields()
    },
    // 点击确认按钮添加角色
    addRoles () {
      this.$refs.rolesFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 如果valid为true就可以发生添加角色的网络请求了
        const { data: res } = await this.$http.post('roles', this.rolesForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        // 添加角色成功后隐藏对话框
        this.addDialogVisible = false
        // 重新获得角色列表数据
        this.getRolesList()
      })
    },
    // 点击修改按钮修改角色信息
    editRoles () {
      this.$refs.editRolesFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        console.log(this.editRolesForm)
        // 如果valid为true就可以发生修改角色的网络请求了
        const { data: res } = await this.$http.put('roles/' + this.editRolesForm.roleId, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改角色失败')
        this.$message.success('修改角色成功')
        // 修改角色成功后隐藏对话框
        this.editDialogVisible = false
        // 重新获得角色列表数据
        this.getRolesList()
      })
    },
    // 点击修改按钮后显示修改角色表单
    async showEditDialog (id) {
      this.editDialogVisible = true
      console.log('当前修改角色的id为' + id)
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询角色信息失败')
      this.editRolesForm = res.data
    },
    // 删除角色
    async removeUserById (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // confirmResult  点击确认返回 confirm
      // confirmResult  点击取消返回 cancel
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 发生删除角色请求
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    },

    // 根据id删除对应的 权限
    async removeRightById (role, rightId) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 发生删除角色请求
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      // this.getRolesList()
      role.children = res.data
    },

    // 分配角色对话框展示
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取权限消息失败！')
      this.rightsList = res.data
      console.log(['当前角色', role])
      // 递归函数调用
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },

    // 递归函数获得所有三级权限的id 并且保存到 defKeys数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 分配对话框关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    //  分配角色框中点击确认为角色分配权限
    async allotRigths () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      console.log(idStr)
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rights', { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败！')
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    }

  }
}
</script>

<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.el-tag {
  margin: 8px;
}

.vcenent {
  display: flex;
  align-items: center;
}
</style>
